<template>
  <div
    class="class-schedule"
    @dragover="dragOverHandle"
    @dragenter="dragenterHandle"
    @dragleave="dragLeaveHandle"
  >
    <table>
      <thead>
        <tr>
          <th>节次/时间</th>
          <th v-for="(weekday, index) in data.weekday" :key="index">
            <span
              class="day"
              :class="currentDate === weekday.date ? 'current' : ''"
              >{{ weekday.day }}</span
            >
            <span>{{ weekday.week }}</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="(timeSlot, index) in data.tite_slot"
          :key="index"
          :data-weekday="timeSlot"
          :data-time-slot="index"
        >
          <th>
            <div class="lable">{{ timeSlot.name }}</div>
            <div class="time">
              {{ timeSlot.startTime }}-{{ timeSlot.endTime }}
            </div>
          </th>
          <td
            v-for="(weekday, weekdayIndex) in data.weekday"
            :key="weekdayIndex"
            :data-weekday="JSON.stringify(weekday)"
            :data-time-slot="JSON.stringify(timeSlot)"
          >
            <!-- :class="initTableData?.[`${weekday.id}-${timeSlot.id}`] ? 'started' : ''" -->
            <!-- 临时处理 -->
            <class-schedule-item
              v-if="initTableData?.[`${weekday.id}-${timeSlot.id}`]"
              :current-data="initTableData?.[`${weekday.id}-${timeSlot.id}`]"
              @operation-handle="operationHandle"
              @delete-handle="deleteHandle"
              @see-preview-handle="seePreview1Handle"
            ></class-schedule-item>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- 课程设置 -->
    <CourseSetList
      :data="currentSelectedData"
      ref="courseSetListRef"
      @edit-handle="editHandle"
      @see-preview-handle="seePreviewHandle"
      @del-course-detail-handle="delCourseDetailHandle"
    ></CourseSetList>
  </div>
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import { type BaseForm } from '../common/WeekBox.vue'
import { type Form } from './FormBar.vue'
import ClassScheduleItem, {
  type CurrentTableData
} from '../common/ClassScheduleItem.vue'
import CourseSetList from '../common/CourseSet/CourseSetList.vue'
import type {
  DataProps,
  CourseSetListItem
} from '../common/CourseSet/CourseSetList.vue'
import type { SaveDragTableData } from '../index.vue'

const props = defineProps<{
  initDateInfo: BaseForm | null
  searchBarInfo: Form | null
  initTableData: Record<string, SaveDragTableData> | null
}>()

interface TiteSlot {
  id: string
  name: string
  semesterId: string
  startTime: string
  endTime: string
}

// 预览数据
const isShowreviewPopup = ref<boolean>(false)
const data = reactive({
  weekday: [
    {
      id: 1,
      week: '星期一',
      day: '',
      date: ''
    },
    {
      id: 2,
      week: '星期二',
      day: '',
      date: ''
    },
    {
      id: 3,
      week: '星期三',
      day: '',
      showDay: ''
    },
    {
      id: 4,
      week: '星期四',
      day: '',
      date: ''
    },
    {
      id: 5,
      week: '星期五',
      day: '',
      date: ''
    },
    {
      id: 6,
      week: '星期六',
      day: '',
      date: ''
    },
    {
      id: 7,
      week: '星期日',
      day: '',
      date: ''
    }
  ],
  tite_slot: [] as TiteSlot[]
})

const courseSetListRef = ref()
const currentDate = dayjs().format('YYYY-MM-DD')
const currentSelectedData = ref<DataProps>({
  courseScheduleId: '',
  id: '',
  num: 0
})

const editCurrentDataInfo = ref<CourseSetListItem>()

const setWeekDay = (dateInfo: BaseForm) => {
  const { weekDates } = dateInfo
  weekDates.forEach((date, index) => {
    const day = date.split('-')[2]
    data.weekday[index].date = date
    data.weekday[index].day = day
  })
}

let targetCell: HTMLElement | null = null
// 拖拽经过时
const dragOverHandle = (event: DragEvent) => {
  //  去除默认行为
  event.preventDefault()
}
const Emit = defineEmits<{
  (e: 'dragenterHandle', data: HTMLElement | null): void
  (e: 'delCourseHandle', data: boolean): void
  (e: 'delCourseDetailHandle'): void
}>()

// 拖拽进入时
const dragenterHandle = (event: DragEvent) => {
  event.preventDefault()
  const tar = event.target as HTMLElement
  const dom = tar.closest('.class-schedule-item') as HTMLElement | null

  // 获取最近的 td 父元素
  const closestTd = tar.closest('td') as HTMLElement | null
  const isInClassScheduleItem = dom !== null

  targetCell = null

  if (isInClassScheduleItem) {
    dom.style.borderColor = '#165DFF'
    targetCell = closestTd
  }
  Emit('dragenterHandle', targetCell)
}

//  拖拽移出时
const dragLeaveHandle = (event: DragEvent) => {
  event.preventDefault()
  const tar = event.target as HTMLElement

  // 获取最近的 class-schedule-item 元素
  const dom = tar.closest('.class-schedule-item') as HTMLElement | null

  // 检查鼠标是否真的移出了 class-schedule-item 元素
  const relatedTarget = event.relatedTarget as HTMLElement | null
  const isStillInItem = relatedTarget?.closest('.class-schedule-item') === dom

  // 只有当鼠标真正移出 class-schedule-item 元素时才清除边框颜色
  if (dom && !isStillInItem) {
    dom.style.borderColor = 'transparent'
  }
}

// 点击设置
const operationHandle = (item: CurrentTableData) => {
  console.log(item, 'itemitemitemitemitem')
  console.log(currentSelectedData.value, 'currentSelectedData.value')
  currentSelectedData.value.courseScheduleId = item.id
  courseSetListRef.value?.openDialog(item)
}

// 获取节次
const getSemesterApi = async () => {
  nextTick(() => {
    data.tite_slot = [
      {
        id: '1984142668204085249',
        name: '上1',
        startTime: '08:00',
        endTime: '08:40',
        semesterId: '1984139593338851328'
      },
      {
        id: '1984142762450096130',
        name: '上2',
        startTime: '09:00',
        endTime: '09:40',
        semesterId: '1984139593338851328'
      },
      {
        id: '1984142829034672130',
        name: '上3',
        startTime: '10:00',
        endTime: '10:40',
        semesterId: '1984139593338851328'
      },
      {
        id: '1984142915164704770',
        name: '下1',
        startTime: '14:30',
        endTime: '15:10',
        semesterId: '1984139593338851328'
      },
      {
        id: '1984143020861165570',
        name: '下2',
        startTime: '15:18',
        endTime: '16:10',
        semesterId: '1984139593338851328'
      },
      {
        id: '1984143169620545538',
        name: '下3',
        startTime: '16:30',
        endTime: '17:10',
        semesterId: '1984139593338851328'
      },
      {
        id: '1984143528875266049',
        name: '晚1',
        startTime: '19:30',
        endTime: '20:30',
        semesterId: '1984139593338851328'
      }
    ]
  })
}

// 课堂设置 - 编辑
const editHandle = (item: CourseSetListItem) => {
  editCurrentDataInfo.value = item
}

// 课程设置 - 预览
const seePreviewHandle = (item: CourseSetListItem) => {
  console.log(item, 'itemitemitemitemitem')
  isShowreviewPopup.value = true
  nextTick(() => {})
}

// 课程表 - 预览
const seePreview1Handle = (item: CurrentTableData) => {
  currentSelectedData.value.courseScheduleId = item.id
  courseSetListRef.value?.openDialog(item)
}

// 删除课程
const deleteHandle = (item: CurrentTableData) => {
  currentSelectedData.value.courseScheduleId = item.id
  delScheduleApi()
}
// 删除课程
const delCourseDetailHandle = () => {
  Emit('delCourseHandle', true)
}

// 删除课程
const delScheduleApi = () => {}

watch(
  () => props.initDateInfo,
  (newVal) => {
    if (!newVal) return
    setWeekDay(newVal)
  },
  { immediate: true, deep: true }
)
watch(
  () => props.searchBarInfo,
  () => {
    if (!props.searchBarInfo?.semester) return
    getSemesterApi()
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  if (props.searchBarInfo && props.searchBarInfo.semester) {
    getSemesterApi()
  }
})
</script>

<style lang="scss" scoped>
table {
  width: 100%;
  //   border: 1px solid #e5e6eb;
  table-layout: fixed;
  border-collapse: collapse;
  td {
    height: 80px;
    border: 1px solid #fff;
  }
  th {
    border: 1px solid #fff;
  }
  thead {
    tr {
      th {
        font-size: 14px;
        height: 50px;
        color: #1d2129;
        border-color: #e5e6eb;
        border-top: none;
        border-left: none;
        &:nth-last-of-type(1) {
          border-right: none;
        }

        &:nth-child(1) {
          width: 100px;
          color: #4e5969;
        }
        .day {
          display: inline-block;
          width: 30px;
          height: 30px;
          line-height: 30px;
          border-radius: 50%;
          margin-right: 10px;
          text-align: center;
          font-size: 16px;
          &.current {
            color: #fff;
            background-color: #165dff;
          }
        }
      }
    }
  }
  tbody {
    tr {
      th {
        height: 60px;
        background-color: #e8f3ff;
        .lable {
          font-size: 14px;
          color: #1d2129;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
        .time {
          font-size: 12px;
          color: #86909c;
          margin-top: 5px;
        }
      }
      td {
        height: 60px;
        background-color: #f2f3f5;
      }
    }
  }
}
</style>
